﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Zj.OpenAuth.Domain.Core;
using Zj.OpenAuth.Domain.Interface;
using Zj.OpenAuth.DTO.Common;

namespace Zj.OpenAuth.App.UserApp
{
    /// <summary>
    /// user application service
    /// </summary>
    public class UserAppService : IUserAppService
    {
        public readonly IUserRepository _repository;
        public UserAppService(IUserRepository repository)
        {
            this._repository = repository;
        }


        /// <summary>
        /// add or edit department 
        /// </summary>
        /// <returns></returns>
        public bool AddOrEdit(UserDTO dto, List<int> roleIds)
        {
            User user = Mapper.Map<UserDTO, User>(dto);
            if (dto.Id != 0 && Get(user.Id) != null)
            {
                user = _repository.Get(user.Id);
                user.Account = dto.Account;
                user.RealName = dto.RealName;
                user.Mobile = dto.Mobile;
                user.Email = dto.Email;
                user.Password = dto.Password;
                user.Description = user.Description;

                user.LastModifyTime = DateTime.Now;
                user = _repository.Update(user);
            }
            else
            {
                user = _repository.Insert(user);
            }
            var urms = roleIds.Select(r => new UserRoleMappingDTO() { UserId = dto.Id, RoleId = r }).ToList();
            _repository.UpdateRoleMenu(user.Id, Mapper.Map<List<UserRoleMappingDTO>, List<UserRoleMapping>>(urms));
            return user == null ? false : true;
        }



        /// <summary>
        /// delete department
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public void Delete(int id)
        {
            _repository.Delete(id);
        }


        public void DeleteMuti(List<int> ids)
        {
            ids.ForEach(id => _repository.Delete(id));
        }

        public UserDTO Get(int id)
        {
            return Mapper.Map<User, UserDTO>(_repository.Get(id));
        }


        public List<UserDTO> GetAllList()
        {
            return Mapper.Map<List<User>, List<UserDTO>>(_repository.Query(s => s.Status != StatusEnum.Deleted).ToList());
        }

        public List<UserDTO> GetUsersByDepartment(int? id, int pageIndex, out int rowCount, int pageSize = 10)
        {
            return Mapper.Map<List<User>, List<UserDTO>>(
                _repository.QueryPage(s => s.Status != StatusEnum.Deleted && s.DepartmentId == id.Value, pageSize, pageIndex, out rowCount, s => s.Id)
                .ToList());
        }

        public LoginResult Login(HttpContextBase ctx, string userName, string password)
        {
            var userList = this._repository.Query(u => u.Account.Equals(userName) && u.Status != StatusEnum.Deleted).ToList();
            if (userList == null || userList.Count <= 0)
            {
                return LoginResult.UserNotExist;
            }

            var user = userList.Single();
            if (!user.Password.Equals(password))
            {
                return LoginResult.PasswordError;
            }
            if (user.Status != StatusEnum.Normal)
            {
                return LoginResult.AccountFrozen;
            }
            ctx.Session.Add("CurrentUser",new CurrentUser(userName,password));
            HttpCookie cookie = new HttpCookie(userName, password);
            cookie.Expires = DateTime.Now.AddDays(2);
            ctx.Response.Cookies.Add(cookie);
            return LoginResult.Succeed;
        }
    }
}
